<?php
/**
 * Util
 *
 * @author Ferman Yee <fermanyee@163.com>
 * @copyright 2018-11-6
 */

namespace XppOpenApi\Util;

class Util {

    /**
     * 签名验证
     * @param array $params
     * @return boolean
     */
    public static function checkSign($params = array()) {
        return self::sign($params) === $params['sign'];
    }
    
    /**
     * 签名
     * @param array $params
     * @return string
     */
    public static function sign(&$params = array(), $data = array()) {
        $sign_params = array_merge($params, $data);
        ksort($sign_params);
        
        return strtoupper(md5(self::toUrlParams($sign_params)));
    }
    
    /**
     * 构造URL
     * @param array $params
     * @return string
     */
    public static function toUrlParams($params) {
        $str = '';
        foreach ($params as $k => $v) {
            if ($k != 'sign' && $v != '' && !is_array($v)) {
                $str .= $k . '=' . $v . '&';
            }
        }
        
        $str = trim($str, '&');
        
        return $str;
    }
}
